<?php

namespace app\model;
use app\model\CourierInfo as ModelCourierInfo;
use app\model\DriverInfo as ModelDriverInfo;
use app\model\UserOrder as ModelUserOrder;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\UserOrderLog as ModelUserOrderLog;
use app\model\UserOrderPayLog as ModelUserOrderPayLog;


use think\Db;

class ApplyForSettled extends Common
{
    protected static $obj;

    public function _initialize()
    {
        parent::_initialize();
        $this->db_name = 'apply_for_settled';
    }

    /**
     * 类入口
     * @return ApplyForSettled
     */
    public static function getInstance()
    {
        if (is_null(self::$obj))
            self::$obj = new self();
        return self::$obj;
    }

    /*
     * 入驻申请缴纳押金修改状态
     */
    public function editSettleState($courierId,$type,$amount)
    {
        $where = [
            'map_id' => $courierId,
            'type' => 1,
        ];
        $applyData = Db::name($this->db_name) ->where($where) ->find();
        $bool = false;
        if ($applyData){
            $upData = [
                'settle_type' => $type,
                'state' => 0,
                'describe' => '已缴纳押金',
                'amount' => $amount
            ];
            $res = Db::name($this->db_name)->where(['id'=>$applyData['id']])->update($upData);
            if ($res) $bool = true;
        }
        return $bool;
    }

    /**
     * 快递员审核数量
     */
    public function getToCount($arr_where){
        return Db::name($this->db_name)
            ->where($arr_where)
            ->join('courier_info','apply_for_settled.map_id=courier_info.id')
            ->count();
    }

    /**
     * 快递员审核列表
     */
    public function getCourierAuditList($arr_where,$int_first_row,$int_list_rows,$sort){
        $data = Db::name($this->db_name)
            ->where($arr_where)
            ->field('courier_info.id,courier_info.mobile,courier_info.real_name AS realName,courier_info.gmt_create AS gmtCreate,apply_for_settled.settle_type AS settleType,apply_for_settled.the_number AS theNumber,courier_info.auth_state AS authState,apply_for_settled.state')
            ->join('courier_info','apply_for_settled.map_id=courier_info.id')
            ->limit($int_first_row,$int_list_rows)
            ->order("")
            ->select();
        foreach ($data as $key=>$val){
            if ($val['settleType']==1 or $val['settleType']==2){
                if ($val['state']==0){
                    $data[$key]['theDeposit']="未缴纳";
                }elseif ($val['state']==1){
                    $data[$key]['theDeposit']="已缴纳";
                }
            }elseif ($val['settleType']==3){
                $data[$key]['theDeposit']="免押金";
            }elseif ($val['settleType']==0){
                $data[$key]['theDeposit']="未缴纳";
            }
        }
        return $data;
    }
    /*
     * 生成入驻订单记录
     * type:1:快递员；2：司机；
     */
    public function createRecord($mapId,$type,$amount)
    {
        switch ($type){
            case 1:
                $obj = ModelCourierInfo::getInstance();
                $str = 'KD';//快递
                $module = 'courier';
                break;
            case 2:
                $obj = ModelDriverInfo::getInstance();
                $str = 'SJ';//司机
                $module = 'driver';
                break;
            default:
                _returnError(10014);
                break;
        }
        $bool_res = $obj->toUpdate(['id'=>$mapId],['state'=>2]); //修改快递员或司机入驻状态
        if ($bool_res){
            //判断是否重复申请入驻
            $id = $this->toValue(['map_id' => $mapId, 'type' => $type],'id');

            if (!$id) {
                $data['map_id'] = $mapId;
                $data['type'] = $type;
                $data['real_name'] = $obj->toValue(['id'=>$mapId],'real_name');
                $data['mobile'] = $obj->toValue(['id'=>$mapId],'mobile');
                $data['enter_number'] = $str.date('YmdHis',time()).rand(10000,99999);
                $data['amount'] = $amount ;
                $data['module'] = $module;
                $addId = $this->toAdd($data);

                return $addId;

            } else {
                $update_arr = ['settle_type'=>0,'state'=>0,'amount'=>$amount,'enter_number'=>$str.date('YmdHis',time()).rand(10000,99999)];
                $res = $this->toUpdate(['id' => $id],$update_arr);
                if ($res){
                    return $id;
                }
            }
        }
        _returnError(10010);
    }
    /*
     * 支付宝回调，数据处理 ---快递员及司机入驻
     */
    public function payNotifySet($enterNumber,$settleType)
    {
        $bool_res = $this->toUpdate(['enter_number'=>$enterNumber],['state'=>1,'settle_type'=>$settleType]);
        if ($bool_res)
        {
            $info = $this->toFind(['enter_number'=>$enterNumber]);

            switch ($info['type']){
                case 1:
                    $obj = ModelCourierInfo::getInstance();
                    $payRes = $obj->toUpdate(['id'=>$info['map_id']],['pledge_state'=>$info['state'],'enter_number'=>$enterNumber]);
                    break;
                case 2:
                    $obj = ModelDriverInfo::getInstance();
                    break;

                default:
                    return false;
                    break;
            }
            if ($payRes) return true;

        }else{
            return false;
        }

    }
    /*
     * 用户端下单支付回调
     */
    public function userOrderNotifySet($paySn,$enterNumber,$payType)
    {
        $orderInfo = ModelUserOrder::getInstance()->toFind(['order_sn'=>$enterNumber]);
        $editRes = ModelUserOrder::getInstance()->toUpdate(['order_sn'=>$enterNumber],['order_state'=>30,'pay_sn'=>$paySn,'pay_type'=>$payType]);
        $editLog = ModelUserOrderLog::getInstance()->addOrderLog($orderInfo['order_id'],4,$orderInfo['user_id']);
        //写入用户付款记录
        ModelUserOrderPayLog::getInstance()->userPayLogAdd($enterNumber,$payType);
        //修改快递员表订单状态
        $nowOrderState = ModelUserOrder::getInstance()->toValue(['order_sn'=>$enterNumber],'order_state');
        $editCourierOrder = ModelCourierOrder::getInstance()->toUpdate(['order_id'=>$orderInfo['order_id'],'is_pick'=>1],['state'=>$nowOrderState,'collect_time'=>$this->_now]);
        if ($editRes && $editLog && $editCourierOrder){
            return true;
        }else{
            return false;
        }

    }
   
}
